const authService = require('../services/authService');
const { AppError } = require('./errorHandler');
const { User, Role, Permission } = require('../models');

const checkAuth = async (ctx, next) => {
  // 1) 从请求头获取令牌
  let token;
  if (ctx.headers.authorization && ctx.headers.authorization.startsWith('Bearer')) {
    token = ctx.headers.authorization.split(' ')[1];
  }

  if (!token) {
    throw new AppError(401, '您尚未登录，请先登录以获取访问权限。');
  }

  // 2) 验证令牌
  const user = await authService.verifyToken(token);

  // 3) 授予访问权限
  ctx.state.user = user;
  await next();
};

const checkPermission = (requiredPermissions = []) => {
  return async (ctx, next) => {
    const { user } = ctx.state;

    // 如果用户是超级管理员，直接放行
    if (user.role === 'admin') {
      return next();
    }

    // 获取用户的所有角色和权限
    const userWithRoles = await User.findByPk(user.id, {
      include: [{
        model: Role,
        include: [Permission]
      }]
    });

    // 收集用户所有角色的权限
    const userPermissions = new Set();
    userWithRoles.Roles.forEach(role => {
      role.Permissions.forEach(permission => {
        userPermissions.add(permission.code);
      });
    });

    // 检查是否具有所需的所有权限
    const hasAllPermissions = requiredPermissions.every(permission =>
      userPermissions.has(permission)
    );

    if (!hasAllPermissions) {
      throw new AppError(403, '您没有执行此操作的权限');
    }

    await next();
  };
};

module.exports = {
  checkAuth,
  checkPermission
}; 